/**
 * 商品列表页面
 */
import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Modal, Table, Select, Button, message, Dropdown, Progress } from 'antd';
// 移除Node.js path模块导入，使用浏览器兼容的替代方案
import axios from 'axios';
import html2canvas from 'html2canvas';
import { Document, Packer, Paragraph, TextRun, Table as WordTable, TableRow, TableCell } from 'docx';
import { useThemeStore } from '@/stores/themeStore';

// 根据ProductSchema定义的商品数据结构
interface DataType {
  _id: string;
  shopname: string;
  store: string;
  pass: string;
  price: number;
  nums: number;
  tid?: string;
}

interface TypesList {
  _id: string;
  name: string;
}

interface Values {
  _id: string;
  shopname: string;
  store: string;
  pass: string;
  price: number;
  nums: number;
  tid?: string;
}

interface ErrorItem {
  row: number;
  error: string;
  data: Record<string, string>;
}

const ProductList: React.FC = () => {
  const [form] = Form.useForm()
  const [form1] = Form.useForm()
  const themeStore = useThemeStore()
  const isDark = themeStore.getEffectiveTheme() === 'dark'
  const primaryButtonClass = isDark ? 'dark-ant-btn-primary' : ''
  const secondaryButtonClass = isDark ? 'dark-ant-btn' : ''
  const [formValues, setformValue] = useState<Values>({
    _id: '',
    shopname: '',
    store: '',
    pass: '',
    price: 0,
    nums: 0,
  })
  const [open, setOpen] = useState(false)
  const [open1, setOpen1] = useState(false)
  const [product, setProduct] = useState<DataType[]>([])
  // 添加搜索相关状态
  const [allProducts, setAllProducts] = useState<DataType[]>([])
  const [typeList] = useState<TypesList[]>([])
  const [searchText, setSearchText] = useState('')
  const [isLoading] = useState(false)
  const [exportLoading, setExportLoading] = useState(false)
  
  // 批量添加相关状态
  const [uploading] = useState(false);
  const [progress] = useState(0);
  const [batchAddResult, setBatchAddResult] = useState<{
    visible: boolean;
    total: number;
    success: number;
    failed: number;
    errors: ErrorItem[];
  }>({ visible: false, total: 0, success: 0, failed: 0, errors: [] });
  
  // 批量添加商品Modal状态
  const [batchAddModalVisible, setBatchAddModalVisible] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dragRef = useRef<HTMLDivElement>(null);
  
  // 集成FileManager的上传进度管理
  interface UploadProgress {
    filename: string;
    progress: number;
    status: 'uploading' | 'success' | 'error';
    message?: string;
  }
  const [uploadProgressList, setUploadProgressList] = useState<UploadProgress[]>([]);
  
  // 打开批量添加Modal
  const showBatchAddModal = () => {
    setBatchAddModalVisible(true);
    setUploadProgressList([]);
  };
  
  // 关闭批量添加Modal
  const closeBatchAddModal = () => {
    setBatchAddModalVisible(false);
    setUploadProgressList([]);
  };
  
  // 更新上传进度
  const updateProgress = (
    filename: string, 
    progress: number, 
    status?: 'uploading' | 'success' | 'error',
    message?: string
  ) => {
    setUploadProgressList(prev => 
      prev.map(item => 
        item.filename === filename 
          ? { ...item, progress, status: status || item.status, message }
          : item
      )
    );
  };
  
  // 处理文件上传（根据hsl.js和hsl copy.js中的数据结构实现）
  const handleFileUpload = async (fileList: FileList) => {
    const files = Array.from(fileList);
    
    for (const file of files) {
      const progressItem: UploadProgress = {
        filename: file.name,
        progress: 0,
        status: 'uploading'
      };
      setUploadProgressList(prev => [...prev, progressItem]);

      try {
        // 浏览器兼容的文件扩展名获取方法，替代Node.js的path.extname
        const getFileExtension = (filename: string): string => {
          const lastDotIndex = filename.lastIndexOf('.');
          return lastDotIndex >= 0 ? filename.slice(lastDotIndex).toLowerCase() : '';
        };
        
        // 严格按照hsl.js中接口要求，只支持.xlsx和.xls格式
        const fileExt = getFileExtension(file.name);
        if (fileExt !== '.xlsx' && fileExt !== '.xls') {
          message.error(`${file.name} 不是支持的文件格式，请选择Excel文件(.xlsx, .xls)格式！`);
          updateProgress(file.name, 0, 'error', '不支持的文件格式');
          continue;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('updateExisting', 'false');
        formData.append('skipValidation', 'false');
        
        // 调用批量导入接口 - 严格按照hsl.js中的API路径
        const response = await axios.post('http://localhost:3000/hsl/product/batch/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
            updateProgress(file.name, percentCompleted);
          }
        });
        
        updateProgress(file.name, 100, 'success', '上传成功');
        
        const responseData = response.data;
        
        if (responseData.code === 200) {
          // 成功情况 - 严格按照hsl.js中接口返回的数据结构处理
          const resultData = responseData.data || {};
          // 转换错误格式，匹配接口返回的错误结构
          const errors: ErrorItem[] = [];
          if (resultData.errors && Array.isArray(resultData.errors)) {
            resultData.errors.forEach((err: { row: number; errors?: string[]; error?: string; data?: Record<string, unknown> }) => {
              // 处理行级错误信息
              const errorMessages = err.errors ? err.errors.join(', ') : err.error || '数据验证失败';
              errors.push({
                row: err.row,
                error: errorMessages,
                data: err.data ? Object.fromEntries(
                  Object.entries(err.data).map(([k, v]) => [k, String(v)])
                ) : {}
              });
            });
          }
          
          setBatchAddResult({
            visible: true,
            total: resultData.totalRows || 0,
            success: resultData.successRows || 0,
            failed: resultData.failedRows || 0,
            errors: errors
          });
          message.success(responseData.msg || '商品数据批量添加成功');
          // 重新加载商品列表
          getProductList();
        } else {
          // 失败情况
          message.error(responseData.msg || '批量添加失败');
          const errors: ErrorItem[] = [];
          if (responseData.data?.errors && Array.isArray(responseData.data.errors)) {
            responseData.data.errors.forEach((err: { row?: number; errors?: string[]; error?: string; data?: Record<string, unknown> }) => {
              const errorMessages = err.errors ? err.errors.join(', ') : err.error || '数据验证失败';
              errors.push({
                row: err.row || 0,
                error: errorMessages,
                data: err.data ? Object.fromEntries(
                  Object.entries(err.data).map(([k, v]) => [k, String(v)])
                ) : {}
              });
            });
          } else {
            errors.push({ row: 0, error: responseData.msg || '批量添加失败', data: {} });
          }
          
          setBatchAddResult({
            visible: true,
            total: responseData.data?.totalRows || 0,
            success: responseData.data?.successRows || 0,
            failed: responseData.data?.failedRows || 0,
            errors: errors
          });
        }
      } catch (error) {
        console.error('批量添加失败:', error);
        const errorMessage = error instanceof Error 
          ? error.message 
          : '批量添加失败，请检查网络连接或文件格式';
        message.error(errorMessage);
        updateProgress(file.name, 0, 'error', errorMessage);
        
        setBatchAddResult({
          visible: true,
          total: 0,
          success: 0,
          failed: 0,
          errors: [{ row: 0, error: errorMessage, data: {} }]
        });
      }
    }
  };
  
  // 文件拖拽上传处理
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileUpload(files);
    }
  };

  const columns = [
    {
      title: '商品名称',
      dataIndex: 'shopname',
      key: 'shopname'
    },
    {
      title: '商店名称',
      dataIndex: 'store',
      key: 'store'
    },
    {
      title: '商品信息',
      dataIndex: 'pass',
      key: 'pass'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '库存',
      dataIndex: 'nums',
      key: 'nums'
    },
    {
      title: '操作',
      key: 'operation',
      dataIndex: 'operation',
      render: (_: string, record: DataType) => {
        return (
          <div>
            <Button type="primary" onClick={() => handelEdit(record)}>编辑</Button>
            <Button danger onClick={() => handelDel(record._id)}>删除</Button>
          </div>
        )
      }
    }
  ]
  useEffect(() => {
    getProductList()
  },[])
  
  const getProductList = async () =>{
    const res =  await axios.post('http://localhost:3000/hsl/product/list')
    console.log(res.data)
    // 存储完整数据到 allProducts
    setAllProducts(res.data.data)
    setProduct(res.data.data)
  }

  const handelDel = async(id:string)=>{
    await axios.delete(`http://localhost:3000/hsl/product/delete/${id}`)
    getProductList()
  }

  // 导出为Excel (CSV格式)
  const exportToExcel = () => {
    setExportLoading(true);
    try {
      // 准备CSV数据
      const headers = ['商品名称', '商店名称', '商品信息', '价格', '库存'];
      const rows = [headers];
      
      // 添加数据行
      product.forEach(item => {
        rows.push([
          item.shopname,
          item.store,
          item.pass,
          item.price.toString(),
          item.nums.toString()
        ]);
      });
      
      // 生成CSV内容
      const csvContent = rows.map(row => 
        row.map(cell => `"${cell}"`).join(',')
      ).join('\n');
      
      // 创建下载链接
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `商品列表_${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      
      message.success('Excel导出成功');
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error('导出Excel失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为图片
  const exportToImage = async () => {
    setExportLoading(true);
    try {
      // 创建一个临时的容器来渲染表格数据
      const tableContainer = document.createElement('div');
      tableContainer.style.width = '800px';
      tableContainer.style.padding = '20px';
      tableContainer.style.backgroundColor = 'white';
      tableContainer.style.position = 'absolute';
      tableContainer.style.left = '-9999px';
      tableContainer.style.top = '-9999px';
      document.body.appendChild(tableContainer);

      // 添加标题
      const title = document.createElement('h2');
      title.textContent = '商品列表';
      title.style.textAlign = 'center';
      title.style.marginBottom = '20px';
      tableContainer.appendChild(title);

      // 添加生成时间
      const timeInfo = document.createElement('p');
      timeInfo.textContent = `生成时间: ${new Date().toLocaleString('zh-CN')}`;
      timeInfo.style.textAlign = 'center';
      timeInfo.style.marginBottom = '20px';
      tableContainer.appendChild(timeInfo);

      // 创建表格
      const table = document.createElement('table');
      table.style.width = '100%';
      table.style.borderCollapse = 'collapse';
      
      // 创建表头
      const thead = document.createElement('thead');
      const headerRow = document.createElement('tr');
      const headers = ['商品名称', '商店名称', '商品信息', '价格', '库存'];
      headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        th.style.border = '1px solid #ddd';
        th.style.padding = '10px';
        th.style.backgroundColor = '#f5f5f5';
        th.style.fontWeight = 'bold';
        headerRow.appendChild(th);
      });
      thead.appendChild(headerRow);
      table.appendChild(thead);

      // 创建表格内容
      const tbody = document.createElement('tbody');
      product.forEach(item => {
        const row = document.createElement('tr');
        const data = [item.shopname, item.store, item.pass, item.price.toString(), item.nums.toString()];
        data.forEach(cellText => {
          const td = document.createElement('td');
          td.textContent = cellText;
          td.style.border = '1px solid #ddd';
          td.style.padding = '10px';
          row.appendChild(td);
        });
        tbody.appendChild(row);
      });
      table.appendChild(tbody);
      tableContainer.appendChild(table);

      // 使用html2canvas截图
      const canvas = await html2canvas(tableContainer, {
        scale: 2, // 提高清晰度
        useCORS: true,
        backgroundColor: 'white'
      });

      // 转换为图片并下载
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = `商品列表_${new Date().toISOString().split('T')[0]}.png`;
      link.click();

      // 清理临时元素
      document.body.removeChild(tableContainer);
      message.success('图片导出成功');
    } catch (error) {
      console.error('导出图片失败:', error);
      message.error('导出图片失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为Word
  const exportToWord = async () => {
    setExportLoading(true);
    try {
      // 创建Word文档
      const doc = new Document({
        sections: [
          {
            properties: {},
            children: [
              // 添加标题
              new Paragraph({
                children: [
                  new TextRun({
                    text: '商品列表',
                    bold: true,
                    size: 36,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 添加生成时间
              new Paragraph({
                children: [
                  new TextRun({
                    text: `生成时间: ${new Date().toLocaleString('zh-CN')}`,
                    size: 20,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 创建表格
              new WordTable({
                rows: [
                  // 表头行
                  new TableRow({
                    children: [
                      new TableCell({
                        children: [new Paragraph('商品名称')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph('商店名称')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph('商品信息')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph('价格')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph('库存')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                    ],
                  }),
                  // 数据行
                  ...product.map(item =>
                    new TableRow({
                      children: [
                        new TableCell({
                          children: [new Paragraph(item.shopname)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(item.store)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(item.pass)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(item.price.toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(item.nums.toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                      ],
                    })
                  ),
                ],
              }),
            ],
          },
        ],
      });

      // 生成Word文件并下载
      const blob = await Packer.toBlob(doc);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `商品列表_${new Date().toISOString().split('T')[0]}.docx`;
      link.click();

      message.success('Word导出成功');
    } catch (error) {
      console.error('导出Word失败:', error);
      message.error('导出Word失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 搜索相关处理函数
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value)
  }

  const handleSearch = () => {
    if (!searchText.trim()) {
      setProduct(allProducts)
      return
    }

    const filtered = allProducts.filter(item => {
      const searchLower = searchText.toLowerCase()
      return (
        item.shopname.toLowerCase().includes(searchLower) ||
        item.store.toLowerCase().includes(searchLower) ||
        item.pass.toLowerCase().includes(searchLower) ||
        String(item.price).includes(searchText) ||
        String(item.nums).includes(searchText)
      )
    })
    setProduct(filtered)
  }

  const handleReset = () => {
    setSearchText('')
    setProduct(allProducts)
  }
    
  // 关闭批量添加结果弹窗
  const handleCloseBatchResult = () => {
    setBatchAddResult(prev => ({ ...prev, visible: false }))
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch()
    }
  }

  const handelEdit = (record: DataType) => {
    setformValue(record)
    // 使用 form.setFieldsValue 确保表单显示正确的值
    form.setFieldsValue(record)
    console.log(record)
    setOpen(true)
  }
  // console.log(formValues)
  const handelSubmit = async () => {
    try {
      // 获取表单最新值
      const values = await form.validateFields();
      // 确保包含 _id
      console.log(values, '23223')
      const updatedValues = { ...values, _id: formValues._id };
      console.log('提交的数据:', updatedValues);
      await axios.put(`http://localhost:3000/hsl/product/update/${formValues._id}`, updatedValues);
      getProductList();
      setOpen(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  }
  const handelAdd = async () => {
    try {
      const values = await form1.validateFields();
      console.log(values)
      await axios.post('http://localhost:3000/hsl/product/add', values);
      getProductList();
      setOpen1(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  }
  return (
    <div className="min-h-screen space-y-6 p-6 bg-gray-50 dark:bg-slate-950 transition-colors">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">商品列表</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">管理所有商品信息</p>
      </div>

      <div className="bg-white dark:bg-slate-900/90 border border-transparent dark:border-slate-800 rounded-lg shadow p-6 transition-colors">
        {/* 搜索和刷新功能 */}
        <div className="mb-4 flex items-center space-x-4">
          <Input
            placeholder="搜索商品名称、商店名称、商品信息、价格或库存"
            value={searchText}
            onChange={handleSearchChange}
            onKeyPress={handleKeyPress}
            className={`w-64 product-filter-input ${isDark ? 'product-filter-input-dark' : ''}`}
            style={{ width: '300px' }}
          />
          <Button
            type="primary"
            onClick={handleSearch}
            className={primaryButtonClass}
          >
            搜索
          </Button>
          <Button
            onClick={handleReset}
            className={secondaryButtonClass}
          >
            重置
          </Button>
          <Button
            type="primary"
            onClick={() => setOpen1(true)}
            disabled={isLoading}
            className={primaryButtonClass}
          >
            添加商品
          </Button>
          
          
          <Button type="primary" onClick={showBatchAddModal} disabled={isLoading || uploading} className={primaryButtonClass}>
            批量添加
          </Button>
          <Dropdown
            menu={{
              items: [
                {
                  key: 'excel',
                  label: '导出Excel',
                  onClick: exportToExcel
                },
                {
                  key: 'image',
                  label: '导出图片',
                  onClick: exportToImage
                },
                {
                  key: 'word',
                  label: '导出Word',
                  onClick: exportToWord
                }
              ]
            }}
            overlayClassName={isDark ? 'dark-ant-dropdown' : undefined}
          >
            <Button
              type="default"
              disabled={isLoading || exportLoading || product.length === 0}
              className={secondaryButtonClass}
            >
              {exportLoading ? '导出中...' : '导出数据'}
            </Button>
          </Dropdown>
        </div>
          
        <Table
          className={isDark ? 'product-table-dark' : 'product-table-light'}
          columns={columns}
          dataSource={product}
          loading={isLoading}
          rowKey="_id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条数据`
          }}
          rowClassName={(_, index) =>
            isDark
              ? index % 2 === 0
                ? 'product-row-dark-even'
                : 'product-row-dark-odd'
              : ''
          }
        />
      </div>
      <Modal
        title="编辑商品信息"
        open={open1}
        onOk={() => handelAdd()}
        onCancel={() => setOpen1(false)}
      >
        <Form form={form1} initialValues={formValues} layout="vertical">
          <Form.Item name="shopname" label="商品名称">
            <Input />
          </Form.Item>
          <Form.Item name="store" label="商店名称">
            <Input />
          </Form.Item>
          <Form.Item name="pass" label="商品信息">
            <Input />
          </Form.Item>
          <Form.Item name="price" label="价格">
            <Input />
          </Form.Item>
          <Form.Item name="nums" label="库存">
            <Input />
          </Form.Item>
          <Form.Item name="tid" label="商品类型">
            <Select
              options={typeList.map(item => ({
                value: item._id,
                label: item.name,
              }))}
              placeholder="请选择商品类型（可选）"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑商品信息"
        open={open}
        onOk={() => handelSubmit()}
        onCancel={() => setOpen(false)}
      >
        <Form form={form} initialValues={formValues} layout="vertical">
          <Form.Item name="shopname" label="商品名称">
            <Input />
          </Form.Item>
          <Form.Item name="store" label="商店名称">
            <Input />
          </Form.Item>
          <Form.Item name="pass" label="商品信息">
            <Input />
          </Form.Item>
          <Form.Item name="price" label="价格">
            <Input />
          </Form.Item>
          <Form.Item name="nums" label="库存">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 批量添加进度显示 */}
      {uploading && progress > 0 && (
        <Modal
          title="批量添加进度"
          open={uploading}
          footer={null}
          closable={false}
        >
          <Progress percent={progress} status="active" />
          <p className="mt-4 text-center">正在处理文件，请稍候...</p>
        </Modal>
      )}
      
      {/* 批量添加商品Modal - 集成FileManager的上传功能 */}
      <Modal
        title="批量添加商品"
        open={batchAddModalVisible}
        onCancel={closeBatchAddModal}
        footer={[
          <Button key="close" onClick={closeBatchAddModal}>
            关闭
          </Button>
        ]}
        width={600}
      >
        <div className="space-y-4">
          <div className="text-gray-600">
            <h3 className="font-medium mb-2">批量添加说明：</h3>
            <ul className="list-disc pl-5 space-y-1">
              <li>请使用Excel文件(.xlsx, .xls)格式上传</li>
              <li>文件大小限制：10MB</li>
              <li>每行数据代表一个商品，支持批量导入多个商品</li>
              <li>请确保数据格式正确，特别是价格和库存必须为数字</li>
            </ul>
          </div>
          
          {/* 文件选择按钮 - 集成FileManager风格 */}
          <div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept=".xlsx,.xls"
              className="hidden"
              onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2"
            >
              📤 选择Excel文件
            </button>
          </div>
          
          {/* 拖拽上传区域 - 集成FileManager功能 */}
          <div
            ref={dragRef}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
            className="border-2 border-dashed border-gray-300 dark:border-slate-700 rounded-lg p-8 text-center hover:border-blue-500 dark:hover:border-blue-400 transition-colors bg-gray-50 dark:bg-slate-900/60"
          >
            <div className="text-4xl mb-2">📁</div>
            <div className="text-gray-600 dark:text-slate-200">拖拽Excel文件到这里上传</div>
            <div className="text-sm text-gray-400 dark:text-slate-400 mt-1">支持.xlsx和.xls格式</div>
          </div>
          
          {/* 上传进度显示 - 集成FileManager风格 */}
          {uploadProgressList.length > 0 && (
            <div className="mt-4">
              <h3 className="font-semibold mb-3">上传进度</h3>
              {uploadProgressList.map((item, index) => (
                <div key={index} className="mb-3">
                  <div className="flex justify-between text-sm mb-1">
                    <span>{item.filename}</span>
                    <span className={
                      item.status === 'success' ? 'text-green-500' :
                      item.status === 'error' ? 'text-red-500' :
                      'text-blue-500'
                    }>
                      {item.status === 'success' ? '✓ ' : item.status === 'error' ? '✗ ' : ''}
                      {item.progress}%
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className={`h-2 rounded-full transition-all ${
                        item.status === 'success' ? 'bg-green-500' :
                        item.status === 'error' ? 'bg-red-500' :
                        'bg-blue-500'
                      }`}
                      style={{ width: `${item.progress}%` }}
                    />
                  </div>
                  {item.message && (
                    <div className="text-xs text-gray-500 mt-1">{item.message}</div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </Modal>
      
      {/* 批量添加结果弹窗 */}
      <Modal
        title="批量添加结果"
        open={batchAddResult.visible}
        onOk={handleCloseBatchResult}
        onCancel={handleCloseBatchResult}
        footer={[
          <Button key="close" onClick={handleCloseBatchResult}>
            关闭
          </Button>
        ]}
        width={600}
      >
        <div className="space-y-4">
          <div>
            <p><strong>总数据行数：</strong>{batchAddResult.total}</p>
            <p><strong>成功添加：</strong><span style={{ color: '#52c41a' }}>{batchAddResult.success}</span></p>
            <p><strong>添加失败：</strong><span style={{ color: batchAddResult.failed > 0 ? '#ff4d4f' : '#333' }}>{batchAddResult.failed}</span></p>
          </div>
          
          {batchAddResult.errors.length > 0 && (
            <div>
              <h4 style={{ color: '#ff4d4f', marginBottom: '12px' }}>错误信息：</h4>
              <div className="bg-gray-100 dark:bg-slate-800/70 p-4 rounded transition-colors">
                {batchAddResult.errors.map((error, index) => (
                  <div key={index} className="mb-2">
                    {error.row > 0 && <span style={{ fontWeight: 'bold' }}>第{error.row}行：</span>}
                    {error.error}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}

export default ProductList

